package net.gilgame.bukkit.commands;

import java.util.List;
import net.gilgame.bukkit.CommandHandler;
import net.gilgame.bukkit.lib.Messages;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;

/**
 *
 * @author Gilgame
 * @date 28 March 2011
 */
public class FindEntity implements ICommand
{
    public boolean run(CommandSender sender, String[] args)
    {
        if (!(sender instanceof Player))
        {
            sender.sendMessage(Messages.NoConsole);
            return true;
        }

        Player player = (Player)sender;

        if (args.length > 1 || args.length < 1)
        {
            sender.sendMessage(Messages.InvalidArguments);
            return false;
        }

        World world = ((Player)sender).getWorld();

        if (world == null)
        {
            sender.sendMessage(Messages.WorldNotFound);
            return true;
        }

        String name = args[0].toLowerCase();

        if (!CommandHandler.hasPermission(sender, "entity." + name))
        {
            sender.sendMessage(Messages.NoEAccess);
            return true;
        }

        List<Entity> entities = world.getEntities();
        Location pLocation = player.getLocation();
        Location eLocation = null;

        for (Entity entity : entities)
        {
            if (entity.getClass().getName().toLowerCase().contains(name))
            {
                if (eLocation != null)
                {
                    double distance = pLocation.distance(entity.getLocation());

                    if (distance < pLocation.distance(eLocation))
                    {
                        eLocation = entity.getLocation();
                    }
                }
                else
                {
                    eLocation = entity.getLocation();
                }
            }
        }

        if (eLocation != null)
        {
            String message = String.format(
                    Messages.MovingToLocation,
                    Math.round(eLocation.getX()),
                    Math.round(eLocation.getY()),
                    Math.round(eLocation.getZ()));
            sender.sendMessage(message);

            player.teleport(eLocation);
        }
        else
        {
            String message = String.format(Messages.EntityNotFound, name);
            sender.sendMessage(message);
        }

        return true;
    }
}
